<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/xizhongren8980/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/xizhongren8980/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/xizhongren8980/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/xizhongren8980/images/logo.svg" color="#222">

<link rel="stylesheet" href="/xizhongren8980/css/main.css">


<link rel="stylesheet" href="/xizhongren8980/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/xizhongren8980/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="参考博文：https:&#x2F;&#x2F;blog.csdn.net&#x2F;qq_42370146&#x2F;article&#x2F;details&#x2F;84842168?utm_source&#x3D;app 过年实在是无聊，就试着学学用Java做做界面，最大的收获就是了解使用.css文件美化界面，虽然美化过后还是丑，但是进步一点是一点吧。">
<meta property="og:type" content="article">
<meta property="og:title" content="Javafx实现拼图小游戏（简易版）">
<meta property="og:url" content="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/03/06/%E6%8B%BC%E5%9B%BE%E5%B0%8F%E6%B8%B8%E6%88%8F/index.html">
<meta property="og:site_name" content="一杯茶一包烟，一个BUG改一天">
<meta property="og:description" content="参考博文：https:&#x2F;&#x2F;blog.csdn.net&#x2F;qq_42370146&#x2F;article&#x2F;details&#x2F;84842168?utm_source&#x3D;app 过年实在是无聊，就试着学学用Java做做界面，最大的收获就是了解使用.css文件美化界面，虽然美化过后还是丑，但是进步一点是一点吧。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://github.com/MisterTian8980/PictureOfMyHexoBlog/raw/master/%E6%8B%BC%E5%9B%BE%E6%B8%B8%E6%88%8F/img1.png">
<meta property="og:image" content="https://github.com/MisterTian8980/PictureOfMyHexoBlog/raw/master/%E6%8B%BC%E5%9B%BE%E6%B8%B8%E6%88%8F/img2.png">
<meta property="og:image" content="https://github.com/MisterTian8980/PictureOfMyHexoBlog/raw/master/%E6%8B%BC%E5%9B%BE%E6%B8%B8%E6%88%8F/img3.png">
<meta property="og:image" content="https://github.com/MisterTian8980/PictureOfMyHexoBlog/raw/master/%E6%8B%BC%E5%9B%BE%E6%B8%B8%E6%88%8F/img4.png">
<meta property="article:published_time" content="2020-03-06T11:50:59.457Z">
<meta property="article:modified_time" content="2020-03-04T08:55:29.825Z">
<meta property="article:author" content="MisterTian">
<meta property="article:tag" content="JavaFX">
<meta property="article:tag" content="拼图游戏">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://github.com/MisterTian8980/PictureOfMyHexoBlog/raw/master/%E6%8B%BC%E5%9B%BE%E6%B8%B8%E6%88%8F/img1.png">

<link rel="canonical" href="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/03/06/%E6%8B%BC%E5%9B%BE%E5%B0%8F%E6%B8%B8%E6%88%8F/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Javafx实现拼图小游戏（简易版） | 一杯茶一包烟，一个BUG改一天</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/xizhongren8980/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">一杯茶一包烟，一个BUG改一天</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">收藏永不停止，学习永不开始</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/xizhongren8980/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/xizhongren8980/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/xizhongren8980/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/xizhongren8980/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/xizhongren8980/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/xizhongren8980/xizhongren8980.git/2020/03/06/%E6%8B%BC%E5%9B%BE%E5%B0%8F%E6%B8%B8%E6%88%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/xizhongren8980/images/head.jpg">
      <meta itemprop="name" content="MisterTian">
      <meta itemprop="description" content="一个小菜鸟">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一杯茶一包烟，一个BUG改一天">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Javafx实现拼图小游戏（简易版）
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-03-06 19:50:59" itemprop="dateCreated datePublished" datetime="2020-03-06T19:50:59+08:00">2020-03-06</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-03-04 16:55:29" itemprop="dateModified" datetime="2020-03-04T16:55:29+08:00">2020-03-04</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>参考博文：<a href="https://blog.csdn.net/qq_42370146/article/details/84842168?utm_source=app" target="_blank" rel="noopener">https://blog.csdn.net/qq_42370146/article/details/84842168?utm_source=app</a></p>
<p>过年实在是无聊，就试着学学用Java做做界面，最大的收获就是了解使用<code>.css</code>文件美化界面，虽然美化过后还是丑，但是进步一点是一点吧。<a id="more"></a></p>
<p>无聊嘛，自然就是要做无聊的事情。于是想到了写个拼图小游戏消磨时间。鉴于自身的能力限制，成品与需求相差有点大，我也不准备继续写下去，还是要多多学习基础才是正事，以后要是能力达到了，可能会继续完善一下。</p>
<p>故撰此文，以示纪念。</p>
<h2 id="首界面制作"><a href="#首界面制作" class="headerlink" title="首界面制作"></a>首界面制作</h2><p>这个界面就很简单了，自己想怎么弄就怎么弄了，美观程度受个人审美影响。我就用我的来做个反面例子吧</p>
<p>如图</p>
<p><img src="https://github.com/MisterTian8980/PictureOfMyHexoBlog/raw/master/%E6%8B%BC%E5%9B%BE%E6%B8%B8%E6%88%8F/img1.png" alt=""></p>
<p>布局是使用两个HBox，一个存放<code>进入游戏</code>按钮，一个存放底部标签，然后再放入一个VBox，设置一下内边距之类的参数就可以了。（限于审美，就只讲布局，美化略过）。代码中的有些按钮是没有添加上去的，主要是不想花过多时间。</p>
<p><strong>参考代码</strong></p>
<pre>
package Game;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.net.MalformedURLException;
import java.net.URL;

/*
 * 首界面
 * */
public class Start_Interface extends Application {
    public void start(Stage mainStage) throws MalformedURLException {

        Button button_easy = new Button("进入游戏");
        button_easy.setPrefSize(150,50);
        Button button_hard = new Button("困难");
        button_hard.setPrefSize(100, 50);
        Button button_hardest = new Button("非常困难");
        button_hardest.setPrefSize(120, 50);
        Label label = new Label("@田氏出品，必属差品！");

        HBox hBox1 = new HBox();//存放按钮
        hBox1.setId("hBox1");
        hBox1.getChildren().addAll(button_easy);
        hBox1.setPadding(new Insets(650, 350, 0, 325));
        hBox1.setSpacing(100);//设置按钮之间的距离
        hBox1.setAlignment(Pos.CENTER);

        HBox hBox2 = new HBox();//存放文本标签
        hBox2.getChildren().addAll(label);
        hBox2.setPadding(new Insets(50,0,500,330));

        VBox vBox = new VBox();//存放hBox1、hBox2
        vBox.getChildren().addAll(hBox1, hBox2);

        Pane pane = new Pane();//存放vBox
        pane.setId("pane1");
        pane.setPrefWidth(800);
        pane.setPrefHeight(800);
        pane.getChildren().add(vBox);
        /*简单游戏难度*/
        button_easy.setOnAction(event -> {
            Game_easy game_easy = new Game_easy();
            game_easy.start(mainStage);

        });

        /*困难游戏难度*/
        button_hard.setOnAction(event -> {

        });
        /*特别困难游戏难度*/
        button_hardest.setOnAction(event -> {

        });

        Scene scene = new Scene(pane, 800, 800);
        URL url = this.getClass().getClassLoader().getResource("Game/Start_Interface.css");//添加css样式的路径
        scene.getStylesheets().add(url.toExternalForm());
        mainStage.setScene(scene);
        mainStage.setTitle("简易的拼图游戏");
        mainStage.setResizable(false);
        mainStage.show();
    }
    public static void main(String args[]) {
        launch(args);
    }
}

</pre>

<h2 id="拼图界面制作"><a href="#拼图界面制作" class="headerlink" title="拼图界面制作"></a>拼图界面制作</h2><p><strong>布局：</strong></p>
<p>左侧是一个GridPane,右侧VBox,整体布局HBox。（注释部分是用于调试的）</p>
<p>界面如图</p>
<p><img src="https://github.com/MisterTian8980/PictureOfMyHexoBlog/raw/master/%E6%8B%BC%E5%9B%BE%E6%B8%B8%E6%88%8F/img2.png" alt=""></p>
<p><strong>参考代码</strong></p>
<pre>
package Game;

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.Rectangle2D;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseDragEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;


import java.awt.event.KeyListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;


public class Game_easy extends Application {

    Button bt_return = new Button("返回首页");
    Button bt_begin = new Button("开始游戏");
    Button bt_changeView = new Button("更换图片");
    Button bt_help = new Button("查看原图");
    Button bt_renew = new Button("复原图片");
    Button bt_music = new Button("播放音乐");
    Label lb_step = new Label("当前步数");
    Label lb_step_text = new Label("0");

    int indexNull = 0;//记录随机空白格的下标
    int step = 0;//记录当前步数
    String s = "";//步数的字符表示
    ImageView[] imageViews = new ImageView[9];//九宫格

    public void start(Stage stage) {
        init(stage);
    }
    public void init(Stage stage) throws IllegalArgumentException {

        lb_step.setAlignment(Pos.CENTER);
        bt_begin.setPrefSize(200,50);
        bt_changeView.setPrefSize(200,50);
        bt_help.setPrefSize(200,50);
        bt_renew.setPrefSize(200,50);
        bt_music.setPrefSize(200,50);
        lb_step.setPrefSize(200,50);
        lb_step.setPrefSize(200,50);
        bt_return.setPrefSize(200,50);
        VBox vBox = new VBox();
        vBox.setId("vBox");
        vBox.setPrefSize(260, 800);
        vBox.getChildren().addAll(bt_begin, bt_changeView, bt_help, bt_renew, bt_music, lb_step,lb_step_text,bt_return);
        vBox.setAlignment(Pos.CENTER);
        vBox.setSpacing(50);


        GridPane gridPane = new GridPane();
        gridPane.setId("gridPane");
        gridPane.setPrefSize(800,800);
        gridPane.setHgap(1);
        gridPane.setVgap(1);
        gridPane.setAlignment(Pos.CENTER);
        gridPane.setGridLinesVisible(true);

        HBox hBox = new HBox();
        hBox.setId("hbox");
        hBox.setSpacing(10);
        hBox.setPadding(new Insets(10));
        hBox.setPrefSize(1060, 800);
        hBox.getChildren().addAll(gridPane, vBox);

//        Pane pane_time = new Pane();
//        pane_time.setId("pane_time");
//        Label lb_time = new Label("剩余时间");
//        pane_time.setPrefSize(1026, 50);
//        pane_time.getChildren().addAll(lb_time);

        VBox vBox_total = new VBox();
        vBox_total.setAlignment(Pos.CENTER);
        vBox_total.setPrefSize(1026, 870);
        vBox_total.getChildren().addAll(hBox);
        vBox_total.setSpacing(10);

        Image image2 = new Image("./Game/img2.png");
        for (int i = 0; i < 9; i++) {
            imageViews[i] = new ImageView(image2);//初始化数组
        }
        //切割图片分给数组
        for (int i = 0, k = 0; i <= 2; i++) {
            for (int j = 0; j <= 2; j++, k++) {
                imageViews[k].setViewport(new Rectangle2D(266*j,266*i,266,266));
            }
        }

        //打乱图片排列顺序
        int[] a = randNum_Is_Du();//这个数组的元素就是图片数组中对应图片的下标
        indexNull = find(a);//这个下标的图片需要改为空白图片
//        System.out.println("空白图片下标"+indexNull);
        int imgViewindex = 0;
        gridPane.add(imageViews[a[0]], 0, 0);
        gridPane.add(imageViews[a[1]], 1, 0);
        gridPane.add(imageViews[a[2]], 2, 0);
        gridPane.add(imageViews[a[3]], 0, 1);
        gridPane.add(imageViews[a[4]], 1, 1);
        gridPane.add(imageViews[a[5]], 2, 1);
        gridPane.add(imageViews[a[6]], 0, 2);
        gridPane.add(imageViews[a[7]], 1, 2);
        //填充空白
        Image imgNull = new Image("./Game/imgNull.png");
        ImageView imageViewNull = new ImageView(imgNull);
        imageViewNull.setFitHeight(266);
        imageViewNull.setFitWidth(266);
        imageViews[indexNull] = imageViewNull;//这样赋值可以解决出现空白的情况
        gridPane.add(imageViews[indexNull],2,2);


        //开始游戏
        bt_begin.setOnAction(event -> {
            for (int i = 0; i < imageViews.length; i++) {
                imageViews[i].setOnMouseClicked(new myevent());
            }
        });

        //播放音乐
        bt_music.setOnAction(event -> {
           Music music1 = new Music();
           music1.init(new Stage());
        });

//        bt_renew.setOnAction(event -> {
//            for (int i = 0; i < imageViews.length; i++) {
//                imageViews[i].setOnMouseClicked(new NullEvent());
//            }
//        });

        //查看原图
        bt_help.setOnAction(event -> {
            View_Original_Image original_image = new View_Original_Image();
            original_image.start(new Stage());
        });

        //返回首页
        bt_return.setOnAction(event -> {
            Start_Interface start_interface = new Start_Interface();
            try {
                start_interface.start(stage);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        });

        Scene scene_game_easy = new Scene(vBox_total,1060,870);
        URL url = this.getClass().getClassLoader().getResource("Game/Game_easy.css");//添加css样式的路径
        scene_game_easy.getStylesheets().add(url.toExternalForm());
        stage.setScene(scene_game_easy);
        stage.show();
    }
    //鼠标点击事件的实现
    class myevent implements EventHandler<MouseEvent> {
        public void handle(MouseEvent mouseEvent) {
            ImageView img = (ImageView) mouseEvent.getSource();
            double x = img.getLayoutX();
            double y = img.getLayoutY();
            double dx = (x - imageViews[indexNull].getLayoutX());
            double dy = (y - imageViews[indexNull].getLayoutY());
//            System.out.println("dx: "+dx);
//            System.out.println("dy: "+dy);
            if ((dx == 0) && (dy == -267)) {//点击的是空白格子的上面

                step++;//步数加1
                s = String.valueOf(step);
                lb_step_text.setText(s);
                swap(img, imageViews[indexNull]);
//                System.out.println("点击上面");
                if (isOK(imageViews)) {
                    Game_Win game_win = new Game_Win();
                    game_win.start(new Stage());
                }
            } else if ((dx == 0) && (dy == 267)) {//点击的是空白各自的下面

                step++;//步数加1
                s = String.valueOf(step);
                lb_step_text.setText(s);
                swap(img, imageViews[indexNull]);
//                System.out.println("点击下面");
                if (isOK(imageViews)) {
                    Game_Win game_win = new Game_Win();
                    game_win.start(new Stage());
                }
            } else if ((dx == -267.0) && (dy == 0.0)) {//点击的是在空白各自的左边

                step++;//步数加1
                s = String.valueOf(step);
                lb_step_text.setText(s);
                swap(img, imageViews[indexNull]);
//                System.out.println("点击左面");
                if (isOK(imageViews)) {
                    Game_Win game_win = new Game_Win();
                    game_win.start(new Stage());
                }
            } else if ((dx == 267) && (dy == 0)) {//点击的是在空白各自的右边

                step++;//步数加1
                s = String.valueOf(step);
                lb_step_text.setText(s);
                swap(img, imageViews[indexNull]);
//                System.out.println("点击右面");
                if (isOK(imageViews)) {
                    Game_Win game_win = new Game_Win();
                    game_win.start(new Stage());
                }
            }
        }
    }

    //空的鼠标单击事件
    class NullEvent implements EventHandler<MouseEvent> {
        @Override
        public void handle(MouseEvent event) {

        }
    }

    //随机生成一组逆序数为偶数的序列，返回8个数
    public int[] randNum_Is_Du() {
        int [] a = new int[8];
        while (!isDu(a)) {
            a = randNum();
        }
        return a;
    }

    //利用随机数产生8个0-8中不重复的数
    public int[] randNum() {
        int a[] = new int[8];//作为返回值
        Random random = new Random();
        for (int i = 0; i < 8; i++) {
            a[i] = random.nextInt(9);//只产生0-8中的9个数
            for (int j = 0; j < i; j++) {
                if (a[j] == a[i]) {
                    i--;
                    break;
                }
            }
        }
        return a;
    }

    //判断一组数的逆序数是否为偶数
    public boolean isDu(int[] a) {
        int sum = 0;
        for (int i = 0; i < a.length-1; i++) {
            for (int j = i+1; j < a.length; j++) {
                if (a[i] > a[j]) {
                    sum++;
                }

            }
        }
//        System.out.println("逆序数为:"+sum);
        if (sum % 2 == 0 && sum != 0) {
            return true;
        } else {
            return false;
        }
    }

    //找出0-8中未出现的数，作为空白格子的下标
    /*当这个数为8时，程序出错*/
    public int find(int[] a) {
        boolean flag = true;
        for (int i = 0; i < a.length; i++) {
            flag = (i == a[0])||(i == a[1])||(i == a[2])||(i == a[3])||
                    (i == a[4])||(i == a[5])||(i == a[6])||(i == a[7]);
            if (!flag) {
                return i;
            }
        }
        return 8;//针对的是3*3
    }

    //交换两个图片
    public void swap(ImageView img1, ImageView img2) {
        int r1 = GridPane.getRowIndex(img1);
        int c1 = GridPane.getColumnIndex(img1);
        int r2 = GridPane.getRowIndex(img2);
        int c2 = GridPane.getColumnIndex(img2);
        GridPane.setRowIndex(img1,r2);
        GridPane.setColumnIndex(img1, c2);
        GridPane.setRowIndex(img2, r1);
        GridPane.setColumnIndex(img2, c1);
    }

    //判断是否拼图成功
    public boolean isOK(ImageView[] imageViews) {
        for (int i = 0; i < 9; i++) {
            if (i != 3*GridPane.getRowIndex(imageViews[i]) + GridPane.getColumnIndex(imageViews[i])) {
                return false;
            }
        }
        for (int i = 0; i < imageViews.length; i++) {//解除图片的鼠标事件，图片无法交换
                imageViews[i].setOnMouseClicked(new NullEvent());
            }
        return true;
    }
}


</pre>

<h2 id="查看原图界面"><a href="#查看原图界面" class="headerlink" title="查看原图界面"></a>查看原图界面</h2><p>如图</p>
<p><img src="https://github.com/MisterTian8980/PictureOfMyHexoBlog/raw/master/%E6%8B%BC%E5%9B%BE%E6%B8%B8%E6%88%8F/img3.png" alt=""></p>
<p><strong>参考代码</strong></p>
<pre>
package Game;
/*
* 用于查看原图，点击“查看原图”按钮触发该事件
* */
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.net.URL;


public class View_Original_Image extends Application {
    public void init(Stage stage) {
        start(stage);
    }

    public void start(Stage stage) {
        Button bt_continue = new Button("继续游戏");

        Pane pane_Img = new Pane();//显示图片的面板
        pane_Img.setId("pane_Img");
        pane_Img.setPrefSize(600, 600);//图片统一显示为600*600
        ImageView originalImg = new ImageView("./Game/img2.png");
        originalImg.setFitWidth(600);
        originalImg.setFitHeight(600);
        pane_Img.getChildren().addAll(originalImg);

        HBox hBox_bt = new HBox();//显示按钮的面板
        hBox_bt.setId("hBox_bt");
        hBox_bt.getChildren().addAll(bt_continue);
        hBox_bt.setAlignment(Pos.CENTER);

        VBox vBox = new VBox();//父面板
        vBox.setPrefSize(600,650);//图片占600高，按钮50
        vBox.setSpacing(10);//距离10
        vBox.getChildren().addAll(pane_Img, hBox_bt);
        vBox.setPadding(new Insets(10,0,10,10));//内边距10


        //继续游戏按钮事件
        bt_continue.setOnAction(event -> {
            stage.close();
        });

        Scene scene = new Scene(vBox,610,650);
        URL url = this.getClass().getClassLoader().getResource("Game/View_Original_Image.css");//添加css样式的路径
        scene.getStylesheets().add(url.toExternalForm());
        stage.setResizable(false);
        stage.setScene(scene);
        stage.show();
    }
}

</pre>

<h2 id="拼图成功提示界面"><a href="#拼图成功提示界面" class="headerlink" title="拼图成功提示界面"></a>拼图成功提示界面</h2><p>如图</p>
<p><img src="https://github.com/MisterTian8980/PictureOfMyHexoBlog/raw/master/%E6%8B%BC%E5%9B%BE%E6%B8%B8%E6%88%8F/img4.png" alt=""></p>
<p><strong>参考代码</strong></p>
<pre>
package Game;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.net.URL;


public class Game_Win extends Application {
    public void init(Stage stage) {
        start(stage);
    }

    public void start(Stage stage) {
        Label label1 = new Label("恭喜你拼图成功！");
        VBox vBox = new VBox();
        vBox.setId("vBox");
//        vBox.setPadding(new Insets(10));
        vBox.setSpacing(10);
        vBox.getChildren().addAll(label1);
        vBox.setAlignment(Pos.CENTER);
        Scene scene = new Scene(vBox,400,150);
        URL url = this.getClass().getClassLoader().getResource("Game/Game_Win.css");//添加css样式的路径
        scene.getStylesheets().add(url.toExternalForm());
        stage.setScene(scene);
        stage.show();
    }
}

</pre>


<h2 id="音乐播放实现"><a href="#音乐播放实现" class="headerlink" title="音乐播放实现"></a>音乐播放实现</h2><p>布局省略</p>
<p><strong>参考代码</strong></p>
<pre>
package Game;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;

public class Music extends Application {
    public void init(Stage stage) {
        start(stage);
    }
    public void start(Stage stage) {

        Button button = new Button("播放");
        Button button1 = new Button("暂停");
        VBox vBox = new VBox();
        vBox.setSpacing(10);
        vBox.getChildren().addAll(button, button1);

        String s1 = Music.class.getResource("./Twinbed - Trouble I'm In.mp3").toString();
        Media media = new Media(s1);
        MediaPlayer mediaPlayer = new MediaPlayer(media);

        button.setOnAction(event -> {
            mediaPlayer.play();
        });
        button1.setOnAction(event -> {
            mediaPlayer.pause();
        });
        Scene scene = new Scene(vBox);
        stage.setScene(scene);
        stage.show();
    }
}

</pre>

<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>虽然程序简陋，但是也是自己一行行写下来的，只要能学到之前不会的知识就不算浪费时间。</p>
<p>本来想写下拼图复原的算法，但是好像自己能力还不够，以后争取写下。（哈哈）</p>
<p>每天进步一点点。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/xizhongren8980/tags/JavaFX/" rel="tag"># JavaFX</a>
              <a href="/xizhongren8980/tags/%E6%8B%BC%E5%9B%BE%E6%B8%B8%E6%88%8F/" rel="tag"># 拼图游戏</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/xizhongren8980/2020/03/06/%E5%A4%A7%E6%88%98%E7%97%85%E6%AF%92%E6%90%9E%E7%AC%91%E5%8A%A8%E7%94%BB/" rel="prev" title="编码贺新年">
      <i class="fa fa-chevron-left"></i> 编码贺新年
    </a></div>
      <div class="post-nav-item">
    <a href="/xizhongren8980/2020/03/06/Hexo%E9%83%A8%E7%BD%B2/" rel="next" title="Hexo个人博客部署到Github">
      Hexo个人博客部署到Github <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#首界面制作"><span class="nav-number">1.</span> <span class="nav-text">首界面制作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#拼图界面制作"><span class="nav-number">2.</span> <span class="nav-text">拼图界面制作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查看原图界面"><span class="nav-number">3.</span> <span class="nav-text">查看原图界面</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#拼图成功提示界面"><span class="nav-number">4.</span> <span class="nav-text">拼图成功提示界面</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#音乐播放实现"><span class="nav-number">5.</span> <span class="nav-text">音乐播放实现</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">6.</span> <span class="nav-text">总结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="MisterTian"
      src="/xizhongren8980/images/head.jpg">
  <p class="site-author-name" itemprop="name">MisterTian</p>
  <div class="site-description" itemprop="description">一个小菜鸟</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/xizhongren8980/archives/">
        
          <span class="site-state-item-count">57</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/xizhongren8980/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/xizhongren8980/tags/">
          
        <span class="site-state-item-count">101</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://mistertian8980.github.io/" title="https:&#x2F;&#x2F;mistertian8980.github.io&#x2F;" rel="noopener" target="_blank">Github博客</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">MisterTian</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script size="300" alpha="0.6" zIndex="-1" src="/xizhongren8980/lib/canvas-ribbon/canvas-ribbon.js"></script>
  <script src="/xizhongren8980/lib/anime.min.js"></script>
  <script src="/xizhongren8980/lib/velocity/velocity.min.js"></script>
  <script src="/xizhongren8980/lib/velocity/velocity.ui.min.js"></script>

<script src="/xizhongren8980/js/utils.js"></script>

<script src="/xizhongren8980/js/motion.js"></script>


<script src="/xizhongren8980/js/schemes/pisces.js"></script>


<script src="/xizhongren8980/js/next-boot.js"></script>


  <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/three.min.js"></script>
    <script defer src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/canvas_lines.min.js"></script>


  




  
<script src="/xizhongren8980/js/local-search.js"></script>













  

  

</body>
</html>
